import {
  Component,
  OnInit,
  AfterViewInit,
  ViewChild,
  ElementRef
} from '@angular/core'
import { TranslateService } from '@ngx-translate/core'
import {
  AuthGuardService,
  tabListObj,
  galleryInfoObject
} from '../@core/auth-guard-service.guard'
import { LoadingService } from 'ng-devui/loading'
import { GetCollectionService } from '../@core/get-collection.service'
import { SelectAvatarTypeComponent } from './select-avatar-type/select-avatar-type.component'
import { DialogService } from 'ng-devui'
import { ManageService } from '../@core/manage.service'
import { Collection, Tab } from '../@core/interface/manage'
import { Router } from '@angular/router'
import { DrawerService, IDrawerOpenResult } from 'ng-devui/drawer';
import { OrderComponent } from './order/order.component'
import { OrderManageService } from '../@core/order-manage.service'

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
  @ViewChild('imgCon', { static: true }) imgConRef: ElementRef
  @ViewChild('leftArrow', { static: true }) leftArrowRef: ElementRef
  @ViewChild('rightArrow', { static: true }) rightArrowRef: ElementRef
  queryParams = {
    page: 1,
    pageSize: 8,
    collectionStatus: -1
  }

  constructor(
    private translate: TranslateService,
    private authGuardService: AuthGuardService,
    private loadingService: LoadingService,
    private dialogService: DialogService,
    private manageService: ManageService,
    private router: Router,
    private drawerService: DrawerService,
    private orderManageService: OrderManageService,
    private getCollectionService: GetCollectionService
  ) { }

  topCollectionArr = [
    {
      collectionIndex: 'XX XXXX XXXX XXXX',
      collectionName: '暂无数字藏品',
      url: '../../assets/img/home/default.png',
      subCollectionIndex: 0,
      pictureName: ''
    }
  ]
  drawer: IDrawerOpenResult;
  collectionList = []
  recommendList = []
  i18nValues: any //国际化变量
  //数字藏品首页右侧顶部默认头像
  userId = parseInt(localStorage.getItem('userId'))
  digitalAvatarList: string[] = []
  tabList: tabListObj[] = []
  imgList: Array<galleryInfoObject> = []
  showLoading: any
  imgConEle: any
  timer: any = null
  i: number = 0
  curIndex = 0
  autoplay = true
  isClickRecieve: boolean = false
  avatarType = ''
  totalNum = 0
  // 进度条数值
  progressNum = 0
  // 轮播定时器
  myLunBoTimer
  // 定时器时间
  timerTime = 10000
  currentIndex = 0
  // 限时抢购tab
  currentTab = 'recommend'
  tabsLists: Tab[] = [
    {
      id: 'recommend',
      text: '推荐',
      value: -1
    },
    {
      id: 'comingSoon',
      text: '即将开售',
      value: 4
    },
    {
      id: 'rushBuying',
      text: '抢购中',
      value: 5
    },
    {
      id: 'ended',
      text: '已结束',
      value: 6
    }
  ]

  private _currentItem: Collection

  public get currentItem() {
    return this._currentItem
  }

  private set currentItem(val) {
    this._currentItem = val
    this.progressNum = 0
    clearInterval(this.myLunBoTimer)
    this.myLunBoFn()
  }

  ngOnInit(): void {
    this.firstGetCollectionRecommend()
    this.getList()
    this.i18nValues = this.translate.instant('home')
  }

  toPage() {
    this.router.navigate(['/market'])
  }

  changeTab(item: Tab) {
    this.currentTab = item.id
    this.queryParams.collectionStatus = item.value
    this.getList()
  }

  mouseEnter() {
    clearInterval(this.myLunBoTimer)
  }

  mouseLeave() {
    this.myLunBoFn()
  }

  changeItem(item: Collection) {
    this.currentItem = item
    this.currentIndex = this.topCollectionArr.findIndex((ite: Collection) => {
      return ite.collectionIndex === item.collectionIndex && ite.subCollectionIndex === item.subCollectionIndex
    })
  }

  myLunBoFn() {
    this.myLunBoTimer = setInterval(() => {
      if (this.progressNum < 100) {
        this.progressNum++
      } else {
        clearInterval(this.myLunBoTimer)
        if (this.currentIndex < this.topCollectionArr.length - 1) {
          this.currentIndex++
        } else {
          this.currentIndex = 0
        }
        this.currentItem = this.topCollectionArr[this.currentIndex]
      }
    }, this.timerTime / 100)
  }

  firstGetCollectionRecommend() {
    this.manageService.collectionRecommend(5).subscribe((res) => {
      if (res.code === 0) {
        this.recommendList = res.data.collection
        if (this.recommendList) {
          this.topCollectionArr = this.recommendList.splice(0, 5)
        }
        this.currentItem = this.topCollectionArr[0]
      }
    })
  }

  getList() {
    this.authGuardService
      .collectionDetail(this.queryParams)
      .subscribe((res) => {
        if (res.code === 0) {
          this.totalNum = res.data.totalNum
          this.collectionList = res.data.collection
        }
      })
  }

  applyFun(id, subId) {
    this.userId = parseInt(localStorage.getItem('userId'))
    let orderData;
    this.showLoading = this.loadingService.open()
    this.orderManageService.applyCollection(this.userId, id, subId).subscribe(
      (succRes) => {
        this.showLoading.loadingInstance.close()
        if (succRes?.code === 0) {
          orderData = succRes.data
          orderData.createdTime = this.getCollectionService.timeTransform(succRes.data.createdTime)
          this.openDrawer(id, subId, orderData)
        } else {
          if (succRes.data?.Identity_Verification === false) {
            this.getCollectionService.openEnquireDialog()
          } else {
            this.authGuardService.showModalPanel('warning', succRes.msg)
          }
        }
      },
      (errRes) => {
        this.showLoading.loadingInstance.close()
        this.getCollectionService.openStandardDialog()
      }
    )
  }

  openPublishDialog(item) {
    const { collectionIndex, collectionName, subCollectionIndex } = item
    const results = this.dialogService.open({
      title: '提示',
      dialogtype: 'warning',
      content: '是否确认购买“' + collectionName + '”？',
      buttons: [
        {
          cssClass: 'primary',
          text: '确认',
          handler: ($event: Event) => {
            this.applyFun(collectionIndex, subCollectionIndex)
            results.modalInstance.hide()
          }
        },
        {
          cssClass: 'primary',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide()
          }
        }
      ]
    })
  }

  isCanGetData = true //不能获取数据

  showMore() {
    window.onscroll = () => {
      let marginBot = 0
      if (document.compatMode === 'CSS1Compat') {
        marginBot =
          document.documentElement.scrollHeight -
          (document.documentElement.scrollTop + document.body.scrollTop) -
          document.documentElement.clientHeight
      } else {
        marginBot =
          document.body.scrollHeight -
          document.body.scrollTop -
          document.body.clientHeight
      }

      if (marginBot < 300) {
        this.getAllList()
      } else {
        this.isCanGetData = true
      }
    }
  }

  getAllList() {
    if (
      this.isCanGetData &&
      this.queryParams.page + 1 <=
      Math.ceil(this.totalNum / this.queryParams.pageSize)
    ) {
      this.queryParams.page += 1
      this.authGuardService
        .collectionDetail(this.queryParams)
        .subscribe((res) => {
          if (res.code === 0) {
            this.isCanGetData = false
            res.data.collection.forEach((item) => {
              this.collectionList.push(item)
            })

            this.collectionList.every((item) => {
              item.percent = parseFloat(
                ((item.remain / item.supplies) * 100).toFixed(2)
              )
              return item
            })
          }
        })
    }
  }

  openDrawer(collectionIndex: string, subCollectionIndex: string, orderData) {
    this.drawer = this.drawerService.open({
      drawerContentComponent: OrderComponent,
      width: '31.25%',
      zIndex: 1000,
      isCover: true,
      fullScreen: true,
      backdropCloseable: false,
      escKeyCloseable: false,
      position: 'right',
      bodyScrollable: true,
      data: {
        collectionIndex,
        orderData,
        subCollectionIndex,
        close: (event) => {
          this.drawer.drawerInstance.hide();
          this.getList()
        }
      }
    })
  }
}
